<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use App\Models\Config;
use App\Models\Plutuspay;
use App\Models\Store;
use App\Models\StoreDetail;
use App\Models\StoreWithDrawal;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\MessageBag;
use Plutuspay\Api\AccountQuery;
use Plutuspay\Api\AccountSharing;
use Plutuspay\Config\PayConfig;

class StoreWithdrawalController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '门店提现申请';
    
    private $status = [
    	1 => '申请中',
	    2 => '同意',
	    3 => '拒绝'
    ];

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StoreWithDrawal());
        
        $grid->column('store.detail', '申请门店')->display(function ($item) {
            return \Arr::get($item, 'name', '');
        });
        $grid->column('price', '金额')->sortable();
        $grid->column('applicant.name', '申请人');
        $grid->column('admin.name', '同意人');
        $grid->column('remark', __('Remark'));
        $grid->column('status', __('Status'))->using($this->status)->dot([1 => 'info', 2 => 'success', 3 => 'danger']);
        $grid->column('created_at', __('Created at'))->sortable();
        
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            //$filter->equal('applicant_id', '申请人')->select(AdminUser::where('store_id', Admin::user()->store_id)->get()->pluck('name', 'id'));
            $filter->equal('store_id', '门店')->select(Store::with(['detail:id,store_id,name'])->get()->pluck('detail.name','id'));
        });
        
        $grid->disableCreateButton();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(StoreWithDrawal::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('store_id', __('Store id'));
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new StoreWithDrawal());

        $form->text('store.detail.name', '申请门店')->disable();
        $form->text('applicant.name', '申请人')->disable();
        $form->currency('price', '金额')->symbol('￥')->required();
        
        $form->hidden('admin_id', __('Admin id'))->default(Admin::user()->id);
        $form->textarea('remark', '申请理由或备注')->rules('max:190');
        $form->radio('status', __('Status'))
            ->options($this->status)
            ->default(1);

        $form->saving(function ($form) {
            if ($form->model()->status >= 2) {
                admin_warning('提示', '请不要重复操作状态');
                return \redirect()->route('store-withdrawals.edit', ['store_withdrawal' => $form->model()->id]);
            }

            $res = $this->withdrawal($form);
            if ($res !== true) {
                admin_warning('提示', $res);
                return \redirect()->route('store-withdrawals.edit', ['store_withdrawal' => $form->model()->id]);
            } else {
            	admin_success('提示', '提现成功');
            }
        });
        
        $form->disableViewCheck();
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableReset();
        
        return $form;
    }
    
    private function withdrawal($form)
    {
        // 提现
        $datas=[];
		$datas['devId'] = 'FIgVcXrz';
		$datas['keyStr'] = '464967566358727a494f41656e6b574b';
		$datas['privateKey'] = config('yzpay.rsaPrivateKey');
		$datas['publicKey'] = config('yzpay.yzPublicKey');
		$datas['notifyUrl'] = 'https://ktvpjapi.isongpd.com/api/notify/receiptYzNotification';
        $payConfig = new PayConfig($datas);
		// 查询总账户余额 余额不足不提现，提醒充值
	    $main_sn = Config::where('name', 'main_sn')->first();
	    if (!isset($main_sn->value) || empty($main_sn->value)) {
	        return '没有设置分账总账号';
	    }
        $query = [
            'merchantId' => $main_sn->value
        ];
        $accountQuery = new AccountQuery($payConfig);
        $queryRes = $accountQuery->index($query);

        if(!isset($queryRes['data']['availableBalance']) || $queryRes['data']['availableBalance'] < $form->model()->price){

	        return '总账户余额不足请充值';
        }
        // 分账接口
        $accountSharing = new AccountSharing($payConfig);
        // 查询接收人账号
        // 门店账号
        $store = StoreDetail::where('store_id', $form->model()->store_id)->first();
        if (is_null($store) || empty($store->merchant_id)) {
            return '分店没有设置账号';
        }
     
        // 请求参数
        $data = [
            'merchantId' => $main_sn->value,
	        'tradeAmount' => $form->model()->price * 100,
	        'receivers' => [['merchantId' => $store->merchant_id,
						        'amount' => $form->model()->price * 100,
					        ]],
	        'commodityInfo' => commodityInfo([
	            'amount' => $form->model()->price * 100,
		        'id' => $form->model()->id
	        ])
        ];
        
$res = [
  "code" => 0,
  "msg" => null,
  "content" => "RJNXpAvT+vovboKOZ3EuvXcoEC2ISD2dc3IBIZ5XPKiriL+vBFZPFSBm3BO/AX1ocKLDFwKjGCHx6ZVFq0u6wG2Nk0piLQWIOx0sVZA8UgR1m1Spi4ryV/tbiwO+xrvzGAFye2nLJxTwFeqdzXn9mSXX9uKTrSiz ▶",
  "signature" => "A6rmJKTNaXXkxnmjs7qEG/GTLSN9Ms1onQV+MoJoA5PECyuQ94SgVGIIGn/M3Zi56Rv/tPCYk2Lk6IKkPQBxcmu+k2E07lbStCVrWHh93pmm8ucFYAPhuRCmvMqy4v6K0L7BkqeCBvX8Qz/SQ+3RYZsR/lMimt7C ▶",
  "data" => [
    "status" => 0,
    "error" => null,
    "accountTradeId" => "000001727849188",
    "receivers" => [
      0 => [
        "type" => "",
        "account" => "562066003550461",
        "amount" => 100,
        "description" => "分到林建",
      ]
    ]
  ]
];

        $res = $accountSharing->index($data);
        
        // 判断返回状态
        $code = $res['code'];
        if(!empty($res['data'])){
            $status = $res['data']['status'];
        } else {
            $status = 1;
        }
        
        if($code !== $status) {
            // 保存请求记录到plutuspays
            $this->PlutuspaySave($form, $data, $res, 3);
			
            return '提现失败....';
        } else {
        	// 提现成功
            // 保存请求记录到plutuspays
            $this->PlutuspaySave($form, $data, $res, 2);
            
            return true;
        }
    }
    
    // 保存请求记录
    private function PlutuspaySave($form, $data, $res, $status = 2)
    {
        // 保存请求记录到plutuspays表
        $plData = [
        	'number' => '',
	        'type' => 7, //分账提现
	        'price' => $form->model()->price * 100,
	        //'user_id' => '',
	        'json' => json_encode($data),
	        'status' => $status,
	        'notify' => json_encode($res)
        ];
        Plutuspay::create($plData);
    }
}
